package com.ruoyi.common.tenant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.tenant.component.TenantDataSourceManager;
import com.ruoyi.common.tenant.domain.SysTenant;
import com.ruoyi.common.tenant.mapper.SysTenantMapper;
import com.ruoyi.common.tenant.service.ISysTenantService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 租户Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-13
 */
@Service
public class SysTenantServiceImpl implements ISysTenantService {
    @Resource
    private SysTenantMapper sysTenantMapper;
    @Resource
    @Lazy
    private TenantDataSourceManager tenantDataSourceManager;

    /**
     * 查询租户
     *
     * @param id 租户主键
     * @return 租户
     */
    @DS("tenant")
    @Override
    public SysTenant selectSysTenantById(Long id) {
        return sysTenantMapper.selectSysTenantById(id);
    }

    /**
     * 查询租户列表
     *
     * @param sysTenant 租户
     * @return 租户
     */
    @DS("tenant")
    @Override
    public List<SysTenant> selectSysTenantList(SysTenant sysTenant) {
        return sysTenantMapper.selectSysTenantList(sysTenant);
    }

    /**
     * 新增租户
     *
     * @param sysTenant 租户
     * @return 结果
     */
    @DS("tenant")
    @Override
    public int insertSysTenant(SysTenant sysTenant) {
        sysTenant.setCreateTime(DateUtils.getNowDate());
        sysTenant.setMd5(DigestUtils.md5Hex(JSON.toJSONString(sysTenant)));
        int i = sysTenantMapper.insertSysTenant(sysTenant);
        tenantDataSourceManager.refreshDataSource(Collections.singletonList(sysTenant));
        return i;
    }

    /**
     * 修改租户
     *
     * @param sysTenant 租户
     * @return 结果
     */
    @DS("tenant")
    @Override
    public int updateSysTenant(SysTenant sysTenant) {
        sysTenant.setUpdateTime(DateUtils.getNowDate());
        sysTenant.setMd5(DigestUtils.md5Hex(JSON.toJSONString(sysTenant)));
        int i = sysTenantMapper.updateSysTenant(sysTenant);
        tenantDataSourceManager.refreshDataSource(Collections.singletonList(sysTenant));
        return i;
    }

    /**
     * 批量删除租户
     *
     * @param ids 需要删除的租户主键
     * @return 结果
     */
    @DS("tenant")
    @Override
    public int deleteSysTenantByIds(Long[] ids) {
        int i = sysTenantMapper.deleteSysTenantByIds(ids);
        return i;
    }

    /**
     * 删除租户信息
     *
     * @param id 租户主键
     * @return 结果
     */
    @DS("tenant")
    @Override
    public int deleteSysTenantById(Long id) {
        int i = sysTenantMapper.deleteSysTenantById(id);
        return i;
    }
}
